package com.cet6.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cet6.common.Result;
import com.cet6.entity.Word;
import com.cet6.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/words")
public class WordController {
    
    @Autowired
    private WordService wordService;
    
    /**
     * 分页获取单词列表，支持按单词或释义搜索
     * @param page 页码，默认1
     * @param size 每页大小，默认10
     * @param keyword 搜索关键词
     * @return 分页结果
     */
    @GetMapping
    public Result<IPage<Word>> getWords(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword) {
        
        try {
            IPage<Word> wordPage = wordService.getWordPage(page, size, keyword);
            return Result.success("查询成功", wordPage);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取单词详情
     * @param id 单词ID
     * @return 单词详情
     */
    @GetMapping("/{id}")
    public Result<Word> getWordById(@PathVariable Long id) {
        try {
            if (id == null || id <= 0) {
                return Result.error(400, "单词ID不能为空或无效");
            }
            
            Word word = wordService.getWordById(id);
            if (word == null) {
                return Result.error(404, "单词不存在");
            }
            
            return Result.success("查询成功", word);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }
}
